package com.nowcoder.community.service;

import com.nowcoder.community.dao.UserMapper;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 根据id查询用户
    public User findUserById(int id) {
        return userMapper.selectUserById(id);

//        User user = getCache(id);
//        return user != null ? user : initCache(id);
    }

    // 根据username查询用户
    public User findUserByUsername(String username) {
        return userMapper.selectUserByUsername(username);
    }

    // 根据email查询用户
    public User findUserByEmail(String email) {
        return userMapper.selectUserByEmail(email);
    }

    // 更新用户的头像
    public int updateHeader(int id, String headerUrl) {
        return userMapper.updateHeader(id, headerUrl);

//        int rows =  userMapper.updateHeader(id, headerUrl);
//        clearCache(id);
//        return rows;
    }

    // 更新用户的密码
    public Map<String, Object> updatePassword(int userId, String oldPassword, String newPassword) {
        Map<String, Object> map = new HashMap<>();
        // 判空
        if (StringUtils.isBlank(oldPassword)) {
            map.put("oldPasswordMsg", "原密码不能为空！");
            return map;
        }
        if (StringUtils.isBlank(newPassword)) {
            map.put("newPasswordMsg", "新密码不能为空！");
            return map;
        }

        User user = findUserById(userId);
        if (user == null) {
            throw new IllegalArgumentException("参数错误！");
        }
        // 判断原密码是否正确
        oldPassword = CommunityUtil.md5(oldPassword + user.getSalt());
        if (!user.getPassword().equals(oldPassword)) {
            map.put("oldPasswordMsg", "原密码不正确！");
            return map;
        }

        //更新密码
        userMapper.updatePassword(userId, CommunityUtil.md5(newPassword + user.getSalt()));
//        clearCache(userId);

        return map;
    }

    // 获取用户的权限集合
    public Collection<? extends GrantedAuthority> getAuthorities(int userId) {
        User user = findUserById(userId);

        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                switch (user.getType()) {
                    case 1:
                        return CommunityConstant.AUTHORITY_ADMIN;
                    case 2:
                        return CommunityConstant.AUTHORITY_MODERATOR;
                    default:
                        return CommunityConstant.AUTHORITY_USER;
                }
            }
        });
        return list;
    }

//    // 1.优先从缓存中取值
//    private User getCache(int userId) {
//        String userObjectKey = RedisKeyUtil.getUserObjectKey(userId);
//        return (User) redisTemplate.opsForValue().get(userObjectKey);
//    }
//
//    // 2.缓存中取不到时，初始化缓存数据并返回
//    private User initCache(int userId) {
//        User user = userMapper.selectUserById(userId);
//        String userObjectKey = RedisKeyUtil.getUserObjectKey(userId);
//        redisTemplate.opsForValue().set(userObjectKey, user);
//        return user;
//    }
//
//    // 3.数据变更时，清除缓存数据
//    private void clearCache(int userId) {
//        String userObjectKey = RedisKeyUtil.getUserObjectKey(userId);
//        redisTemplate.delete(userObjectKey);
//    }

}
